import React, { useState } from 'react'
import ReactDOM from 'react-dom'
// 引入仓库实列对象
import store from './store/index'

console.log(store.getState())//仓库实列下的方法
class Card extends React.Component{
    constructor() {
        super()
        this.state = {
            fruits: store.getState().cards
        }

        store.subscribe(() => {
            // 会在仓库的数据发生变化时触发
            this.setState({
                fruits: store.getState().cards
            })
        })
    }

    render() {
        return (
            <div>
                <table>
                    <thead>
                        <tr>
                            <th>序号</th>
                            <th>名称</th>
                            <th>价格</th>
                            <th>数量</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        {
                            this.state.fruits.map(item => {
                                return(<tr key={item.id}>
                                    <td>{item.id}</td>
                                    <td>{item.name}</td>
                                    <td>{item.price}</td>
                                    <td>{item.num}</td>
                                    <td>
                                        <button onClick={() => {
                                            this.handelAdd(item)
                                        }}>+</button>
                                        <button onClick={() => {
                                            this.handelDel(item)
                                        }}>-</button>
                                    </td>
                                </tr>)
                            })
                        }
                    </tbody>
                </table>
            </div>
        )
    }

    handelAdd= (item) => {
        store.dispatch({
            type: 'ADD_TODO',
            good: item
        })
    }

    handelDel= (item) => {
        store.dispatch({
            type: 'DEL_TODO',
            good: item
        })
    }
}

const App = () => {
    const [fruits, setFruits] = useState([
        {id: 1, name: '苹果', price: 10},
        {id: 2, name: '香蕉', price: 20},
        {id: 3, name: '李子', price: 30},
        {id: 4, name: '梨子', price: 40}
    ])
    return (
        <div>
            <h1>App</h1>
            <ul>
                {
                    fruits.map((item) => {
                        return (
                            <li key={item.id}>
                                {item.name}
                                <button>+</button>
                                <button>-</button>
                            </li>
                        )
                    })
                }
            </ul>
            <hr/>
            <Card></Card>
        </div>
    )
}

ReactDOM.render(<App/>, document.getElementById('root'))